package cvi.com.reader.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.adapter.ReportGridViewAdapter;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.ReportBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.DateUtil;
import cvi.com.reader.widgets.MyGridView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/8/4.
 * <p>
 * 个人中心-排行榜试听界面
 */

public class PersonalAuditionActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.bb)
    View bb;
    @BindView(R.id.imageview)
    CircleImageView imageview;
    @BindView(R.id.reader)
    TextView reader;
    @BindView(R.id.score)
    TextView score;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.cc)
    ScrollView cc;
    @BindView(R.id.ima_praise)
    LinearLayout imaPraise;
    @BindView(R.id.report_ll)
    LinearLayout reportLl;
    @BindView(R.id.dd)
    View dd;
    @BindView(R.id.progressBar)
    SeekBar progressBar;
    @BindView(R.id.current_time)
    TextView currentTime;
    @BindView(R.id.all_time)
    TextView allTime;
    @BindView(R.id.play)
    Button play;
    @BindView(R.id.praise_num)
    TextView praiseNum;
    @BindView(R.id.gg)
    RelativeLayout gg;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.report_tv)
    TextView reportTv;
    private ChartDataBean.DataBean dataBean = null;
    private int record_id = -1;
    public DialogPlus reportDialog;
    private List<ReportBean.DataBean> dataBeanList = new ArrayList<>();
    private ReportGridViewAdapter reportGridViewAdapter = null;
    private MyGridView myGridView;
    private boolean isPraise = false;
    private int praiseNumb;
    private int reportReanson = -1;
    private boolean isReport = false;
    private MediaPlayer mediaPlayer = new MediaPlayer();//实例化MediaPlayer类
  //  private String strUrl = null;
    private Timer timer = new Timer();
    private int duration;
    private boolean isPause = false;
    private TimerTaskChildren taskChildren;
    private boolean isFinish = false;//是否播放完了
    private String musicUrl;
    private String Tag = "AuditionActivityyyyyyy";
    private LoginBean loginBean;
    /**
     * 线程处理Handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case constant.HANDLER_MESSAGE_WHAT_PLAY_TIME:
                    if (mediaPlayer != null) {
                        currentTime.setText(DateUtil.toVideoTime(mediaPlayer.getCurrentPosition()));
                        progressBar.setProgress(mediaPlayer.getCurrentPosition() / 1000);

                    }
                    Log.d(Tag, "  duration=" + duration + "   mediaPlayer.getCurrentPosition()=" + Math.round(Double.valueOf(String.valueOf(mediaPlayer.getCurrentPosition())) / 1000) + "  进度条秒数" + progressBar.getProgress() / 1000 + "  进度" + mediaPlayer.getCurrentPosition());
                    if (duration == mediaPlayer.getCurrentPosition()) {

                    }
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_audition;
    }

    @Override
    protected void initView() {
        back.setOnClickListener(this);
        imaPraise.setOnClickListener(this);
        reportLl.setOnClickListener(this);
        play.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        if (Hawk.contains("ChartDataBean")) {
            dataBean = Hawk.get("ChartDataBean");
        }

        if (Hawk.contains("LoginBean")) {
            loginBean = Hawk.get("LoginBean");
        }

        if (dataBean != null) {
            ChartDataBean.DataBean.UserBean userBean = dataBean.getUser();
            ChartDataBean.DataBean.MaterialBean materialBean = dataBean.getMaterial();
            reader.setText("朗读者：" + userBean.getRealname());
            score.setText("得分：" + dataBean.getScore() + "");
            content.setText(Html.fromHtml(materialBean.getContent()));
            praiseNum.setText(dataBean.getLikes() + "人已点赞");
            praiseNumb = dataBean.getLikes();
            tittle.setText("《" + materialBean.getMaterial_name() + "》" + "-" + materialBean.getAuthor());
            record_id = dataBean.getId();
            Log.d("dghhgfh", dataBean.getLikes_clicked() + "");
            if (loginBean != null) {
                if (loginBean.getData().getUser_info().getId() == dataBean.getUser_id()) {
                    reportLl.setVisibility(View.GONE);

                }

            }

            if (0 == dataBean.getLikes_clicked()) {
                image.setBackgroundResource(R.mipmap.ic_unpraise);
                isPraise = false;
            } else {
                image.setBackgroundResource(R.mipmap.ic_praise);
                isPraise = true;
            }
            if (1 == dataBean.getTipoff()) {
                reportTv.setText("已举报");
            } else {
                reportTv.setText("举报");
            }
            /*if (Hawk.contains("ip")) {
                strUrl = Hawk.get("ip");
            }
            if (strUrl != null) {

            }*/
            Glide.with(PersonalAuditionActivity.this).load("http://" + constant.URL + userBean.getAvatar()).into(imageview);
            musicUrl = "http://" + constant.URL + dataBean.getMedia_path();
            initPlayer(musicUrl);
        }
//获取举报数据
        getReportData();
    }

    private void initPlayer(String musicUrl) {
        Uri uri = Uri.parse(musicUrl);//网络中的音乐文件
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }
        duration = mediaPlayer.getDuration();//获取音频的时间
        String timelong = duration / 1000 + "s";
        progressBar.setMax(duration / 1000);
        allTime.setText(DateUtil.toVideoTime(duration));
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                Log.d(Tag + "1", "  总时间duration=" + mediaPlayer.getDuration() + "  最终进度" + mediaPlayer.getCurrentPosition() +
                        "  最终秒数" + mediaPlayer.getCurrentPosition() / 1000 + "   进度条=" + progressBar.getProgress() + "  进度条秒数" + progressBar.getProgress() / 1000);
                //  currentTime.setText(DateUtil.toVideoTime(mediaPlayer.getDuration()));
                currentTime.setText("00:00");
                progressBar.setProgress(0);
                play.setBackgroundResource(R.mipmap.ic_auditon_play);
                isFinish = true;
                if (taskChildren != null) {
                    taskChildren.cancel();
                }


            }
        });
    }

    //播放器播放
    public void onPlayerClick(String url) {
        Log.d(Tag, "1111113333" + mediaPlayer.isPlaying() + "    isFinish=" + isFinish);
        play.setBackgroundResource(R.mipmap.ic_audition_puase);
        if (isFinish) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.seekTo(0);
            }
            isFinish = false;
            //  taskChildren.cancel();
        }
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();//播放
        }
        //  mediaPlayer.start();//播放
        taskChildren = new TimerTaskChildren();
        timer.schedule(taskChildren, 0, 1000);
        // musicListAdapter.notifyDataSetChanged();
    }

    //播放器暂停
    public void onPauseClick() {
        Log.d(Tag, "11111122222" + musicUrl);
        if (duration > mediaPlayer.getCurrentPosition()) {
            isPause = true;
            if (taskChildren != null) {
                taskChildren.cancel();
            }

        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//暂停
        }
        // musicListAdapter.notifyDataSetChanged();
    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ima_praise:
                if (dataBean != null) {
                    if (isPraise) {
                        cancelPraise(record_id);
                        isPraise = false;
                    } else {
                        setPraise(record_id);
                        isPraise = true;
                    }
                }

                break;
            case R.id.report_ll:
                if (dataBean != null) {
                    if (1 == dataBean.getTipoff() || isReport) {
                        reportTv.setText("已举报");
                        Toast.makeText(PersonalAuditionActivity.this, "您已举报过了！", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                showDialog();
                break;
            case R.id.play:
                Log.d("mediaPlaying()=", mediaPlayer.isPlaying() + "");

               /* if (isFinish) {
                    Log.d("mediaPlaying()=", mediaPlayer.isPlaying() + "重新播放");
                    Uri uri = Uri.parse("http://" + strUrl + dataBean.getMedia_path());//网络中的音乐文件
                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(this, uri);//音乐文件路径
                        mediaPlayer.prepare();//资源文件准备
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    play.setBackgroundResource(R.mipmap.ic_audition_puase);
                    mediaPlayer.start();//播放
                    taskChildren = new TimerTaskChildren();
                    timer.schedule(taskChildren, 0, 1000);
                    isFinish = false;
                }*/
                if (mediaPlayer.isPlaying()) {//暂停播放
                    onPauseClick();
                    //mediaPlayer.pause();
                    play.setBackgroundResource(R.mipmap.ic_auditon_play);
                } else {//开始播放
                    onPlayerClick(musicUrl);

                }
                break;
        }

    }

    private void setPraise(int record_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().setPraise(record_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PersonalAuditionActivity.this, "点赞成功！", Toast.LENGTH_LONG).show();
                        image.setBackgroundResource(R.mipmap.ic_praise);
                        if (dataBean != null) {
                            if (0 == dataBean.getLikes_clicked()) {
                                praiseNum.setText((dataBean.getLikes() + 1) + "人已点赞");
                                praiseNumb = praiseNumb + 1;
                            }
                        }

                    }
                });
    }

    //取消点赞
    private void cancelPraise(int record_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().canclePraise(record_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PersonalAuditionActivity.this, "取消成功！", Toast.LENGTH_LONG).show();
                        image.setBackgroundResource(R.mipmap.ic_unpraise);
                        if (dataBean != null) {
                            praiseNum.setText((praiseNumb - 1) + "人已点赞");
                            praiseNumb = praiseNumb - 1;
                        }

                    }
                });
    }

    private void showDialog() {
        View view = LayoutInflater.from(PersonalAuditionActivity.this).inflate(R.layout.report_radio_button, null);
        Button reportBtn = view.findViewById(R.id.report_btn);
        myGridView = view.findViewById(R.id.mylistview);
        LinearLayout close_ll = view.findViewById(R.id.close_ll);
        reportDialog = DialogPlus.newDialog(PersonalAuditionActivity.this)
                .setContentHolder(new ViewHolder(view))
                .setCancelable(true)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        reportGridViewAdapter = new ReportGridViewAdapter(PersonalAuditionActivity.this, dataBeanList);
        if (myGridView != null) {
            myGridView.setAdapter(reportGridViewAdapter);
            reportGridViewAdapter.notifyDataSetChanged();
        }
        reportDialog.show();
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ReportBean.DataBean dataBean = (ReportBean.DataBean) adapterView.getAdapter().getItem(i);
                reportGridViewAdapter.setSeclection(i);//传值更新i
                reportGridViewAdapter.notifyDataSetChanged();
                reportReanson = dataBean.getId();
            }
        });
        close_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reportDialog.dismiss();
            }
        });
        reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (-1 == reportReanson) {
                    Toast.makeText(PersonalAuditionActivity.this, "请选择举报原因！", Toast.LENGTH_LONG).show();
                    return;
                }
                setReportData(record_id, reportReanson);
                reportDialog.dismiss();
            }
        });
    }

    private void getReportData() {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().getReportData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        showData(response);
                    }
                });
    }

    private void showData(JSONObject response) {
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            ReportBean.DataBean dataBean = (ReportBean.DataBean) JSONObject.toJavaObject(object, ReportBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            dataBeanList.add(dataBean);
        }

    }

    //举报
    private void setReportData(int record_id, int reason_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().setReport(record_id, reason_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PersonalAuditionActivity.this, "举报成功！", Toast.LENGTH_LONG).show();
                        reportTv.setText("已举报");
                        isReport = true;
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        mHandler.removeMessages(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
        Intent intent = new Intent(constant.CHARTS_MYRECEIVER);
        sendBroadcast(intent);      //发送广播
        if (Hawk.contains("ChartDataBean")) {
            Hawk.delete("ChartDataBean");
        }
        if (taskChildren != null) {
            taskChildren.cancel();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    class TimerTaskChildren extends TimerTask {
        public void run() {

            //  mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
            if (duration / 1000 > Math.round(Double.valueOf(String.valueOf(mediaPlayer.getCurrentPosition())) / 1000)) {
                mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
                if (mediaPlayer != null) {
                    Log.d(Tag, "  音频总时长duration=" + duration + "   progressValue=" + progressBar.getProgress() + "  播放最终进度" + mediaPlayer.getCurrentPosition());
                    Log.d(Tag, mediaPlayer.isPlaying() + "~~~");
                    /*if (mediaPlayer.isPlaying()) {
                        mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
                    }*/
                }

            }/* else {
                mediaPlayer.stop();
                play.setBackgroundResource(R.mipmap.ic_auditon_play);
                progressBar.setProgress(0);
            }*/
        }
    }

}
